package com.qdev.apps.core.webwork.validator;

import java.text.DecimalFormat;

import com.opensymphony.xwork.validator.ValidationException;
import com.opensymphony.xwork.validator.validators.FieldValidatorSupport;

/**
 * Validates a string field using a regular expression.
 * 
 * @author Quake Wang
 * @since 2004-7-23
 * @version $Revision: 1.4 $
 */
public class RegexpFieldValidator extends FieldValidatorSupport {
    private String expression;

    public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        Object value = this.getFieldValue(fieldName, object);
        // if there is no value - don't do comparison
        // if a value is required, a required validator should be added to the field        
        if (value == null)
            return;
        // modify -- not check string instance
        String valueToMatch = value.toString(); 
        // modify -- format maximum number to string type
        if(value instanceof Number) {
            valueToMatch = format((Number)value);
        }
        if (!valueToMatch.matches(expression)) {
            addFieldError(fieldName, object);
        }
    }

    public String getExpression() {
        return expression;
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }
    
    private String format(Number value){
        DecimalFormat df = new DecimalFormat("#0.####");
        return df.format(value.doubleValue());
    }
}